/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version

	@import "poodle"
	@import "poodle/tree"
*/
(function(K){

Coppermine_CatMngr =
{
	tree:null,

	init:function()
	{
		this.tree = $('coppermine_categories');
		if (this.tree) {
			var i=-1, li, nodes = this.tree.$Q('li');
			while (li = nodes[++i]) {
				this.initLI(li);
			}
		}
	},

	initLI:function(li)
	{
		if (li._bm_tree) return;
		li._bm_tree = 1;

		li.attr('draggable','true')
			.bind('selectstart', function(e){e.stop();}) // IE prevent text selection
			.bind('dragstart', function(e) {
				var dt = e.dataTransfer;
				dt.effectAllowed = 'move';
				dt.setData('text', li.attr('data-id'));
				e.stopPropagation();
			})
			.bind('dragenter', function(e){e.stop();})
			.bind('dragover', function(e){
				var dli = e.getDraggingNode();
				if (dli != li && dli.attr('data-id') && 1<li.attr('data-id')) {
					e.dataTransfer.dropEffect = 'move';
					var h = li.clientHeight/4;
					if (h >= li.getMousePos(e).y) {
						dli.before(li);
					} else
					if (h*3 <= li.getMousePos(e).y) {
						dli.after(li);
					} else if (!li.$Q('ul li',1)) {
						li.$Q('ul',1).insertBefore(dli, null);
					}
				} else {
					e.dataTransfer.dropEffect = 'none';
				}
				e.dataTransfer.dropEffect = 'move';
				e.stop();
			})
			.bind('drop', function(e){
				var dli = e.getDraggingNode(), a = li.$Q('a',1),
				 parent = dli.getParentByTagName('li'),
				 prevli = dli.prevElement(),
				   data = ''
					.addQueryParam('move_item', intval(dli.attr('data-id')))
					.addQueryParam('parent_id', parent?intval(parent.attr('data-id')):0)
					.addQueryParam('after_id',  prevli?intval(prevli.attr('data-id')):0);
				a.xhr = new PoodleXHR;
				a.addClass('loading');
				a.xhr.post(null,function(pxhr){
					a.removeClass('loading');
					var data=pxhr.fromJSON();
					if (!data || !data.moved) {
						// put back?
					}
				}, data);
				e.stop();
			});
	}

};

K.onDOMReady(function(){
	Coppermine_CatMngr.init();
//	window.bind('beforeunload',function(e){e.stop()});
});

})(Poodle);
